const express = require("express")
const app = express()
const port = 3000 // 服务端口
const jwt = require('jsonwebtoken')
const jwtKey='JWT_SECRET_KEY'
const Response =require('./utils/Response')

// 配置跨域
const cors = require("cors")
app.use(
  cors({
    origin: "*",
  })
)
const history=require('connect-history-api-fallback')
app.use(history())
// 设置dist为静态托管文件夹
app.use(express.static('dist'))

// 解析post请求参数
app.use(express.urlencoded())


// 自定义token全局验证中间件
const tokenTools=function(req,resp,next){
  // console.log(req.path)
  // 如果请求路径是/user/login 则不拦截直接next
  if(req.path=='/user/login'){
    next()
    return
  }
  let token=req.headers['authorization']
  try {
      let payload=jwt.verify(token,jwtKey)
      // 将token中存储的数据直接给req
      req.tokenPayload=payload
  } catch (error) {
    resp.send(Response.error(401,'用户验证失败,请重新登陆'))
    return
  }
  next()
}
app.use(tokenTools)

// 引入外部路由
app.use(require("./router/MovieActor.js"))
app.use(require("./router/MovieDirector.js"))
app.use(require("./router/MovieInfo.js"))
app.use(require("./router/MovieThumb.js"))
app.use(require("./router/Cinema.js"))
app.use(require("./router/CinemaRoom.js"))
app.use(require('./router/ShowingonPlan.js'))
app.use(require('./router/Admin'))


/**
 * 接口， 处理/请求
 */
app.get("/", (req, resp) => {
  resp.send("Hello World!")
})

app.listen(port, () => {
  console.log("百慕大影城后端服务已启动...")
})
